package com.ft.scan.common;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.google.gson.Gson;
import com.google.gson.internal.bind.JsonTreeReader;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

import com.ft.scan.config.AliConfig;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 阿里云 短信服务 工具类
 */
public class AliNoteUtils {

    private AliConfig aliConfig = new AliConfig();

    AsyncClient client;

    public AliNoteUtils() {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(aliConfig.getACCESS_KEY_ID())
                .accessKeySecret(aliConfig.getACCESS_KEY_SECRET())
                .build());

        client = AsyncClient.builder()
                .region("cn-beijing-finance-1") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();
    }


    /**
     * 实现短信发生功能
     *
     * @param mobile 手机号
     * @return 返回验证码
     */
    public String sendNote(String mobile) {
        //生成4位随机数
        String code = String.valueOf(RandomUtils.nextInt(1000, 9999));
        try {
            SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                    .signName("阿里云短信测试")
                    .templateCode("SMS_154950909")
                    .phoneNumbers(mobile)
                    .templateParam("{\"code\":\"" + code + "\"}")  // 使用字符串拼接替换 code
                    .build();

            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            SendSmsResponse resp = response.get();
//            System.out.println(new Gson().toJson(resp));
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return null;
        }
        return code;
    }

}
